<!--
 * @Author: Mr · Lei
 * @Date: 2024-12-18 17:58:30
 * @LastEditors: OBKoro1
 * @LastEditTime: 2024-12-18 17:58:30
 * @FilePath: \ruituan-tuan-Agent\src\views\income\income-team\index.vue
 * @Description: 
 * 
 * Copyright (c) 2024 by 四川开局红科技有限公司, All Rights Reserved. 
-->
<!--
 * @Author: Mr · Lei
 * @Date: 2024-12-18 17:21:01
 * @LastEditors: OBKoro1
 * @LastEditTime: 2024-12-18 17:21:01
 * @FilePath: \ruituan-tuan-Agent\src\views\team\team-incom\index.vue
 * @Description: 
 * 
 * Copyright (c) 2024 by 四川开局红科技有限公司, All Rights Reserved. 
-->
<template>
  <div class="container">
    <Breadcrumb :items="['menu.team', 'menu.team.income']" />
    <a-card class="general-card" :title="$t('teamIncome.title')">
      <a-row>
        <a-col :span="20">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 4 }"
            :wrapper-col-props="{ span: 18 }"
            label-align="left"
          >
            <a-row :gutter="16">
              <!-- 客户昵称搜索 -->
              <a-col :span="8">
                <a-form-item
                  field="nickname"
                  :label="$t('teamIncome.form.nickname')"
                >
                  <a-input
                    v-model="formModel.nickname"
                    :placeholder="$t('teamIncome.form.placeholder.nickname')"
                  />
                </a-form-item>
              </a-col>
              <!-- 客户电话搜索 -->
              <a-col :span="8">
                <a-form-item
                  field="moblie"
                  :label="$t('teamIncome.form.mobile')"
                >
                  <a-input
                    v-model="formModel.mobile"
                    :placeholder="$t('teamIncome.form.placeholder.mobile')"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-col :span="4" style="text-align: right">
          <a-space :size="18">
            <a-button type="primary" @click="search">
              <template #icon>
                <icon-search />
              </template>
              {{ $t('teamIncome.form.search') }}
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              {{ $t('teamIncome.form.reset') }}
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 10px" />
      <a-row style="margin-bottom: 16px">
        <a-col :span="12">
          <a-space>
            <!-- <a-button type="primary" size="large">
              {{ $t('teamIncome.table.create') }}
            </a-button> -->
            {{ $t('teamIncome.table.title') }}
          </a-space>
        </a-col>
        <a-col
          :span="12"
          style="display: flex; align-items: center; justify-content: end"
        >
          <a-tooltip :content="$t('teamIncome.actions.refresh')">
            <div class="action-icon" @click="search"
              ><icon-refresh size="18"
            /></div>
          </a-tooltip>
          <a-dropdown @select="handleSelectDensity">
            <a-tooltip :content="$t('teamIncome.actions.density')">
              <div class="action-icon"><icon-line-height size="18" /></div>
            </a-tooltip>
            <template #content>
              <a-doption
                v-for="item in densityList"
                :key="item.value"
                :value="item.value"
                :class="{ active: item.value === size }"
              >
                <span>{{ item.name }}</span>
              </a-doption>
            </template>
          </a-dropdown>
          <a-tooltip :content="$t('teamIncome.actions.columnSetting')">
            <a-popover
              trigger="click"
              position="bl"
              @popup-visible-change="popupVisibleChange"
            >
              <div class="action-icon"><icon-settings size="18" /></div>
              <template #content>
                <div id="tableSetting">
                  <div
                    v-for="(item, index) in showColumns"
                    :key="item.dataIndex"
                    class="setting"
                  >
                    <div style="margin-right: 4px; cursor: move">
                      <icon-drag-arrow />
                    </div>
                    <div>
                      <a-checkbox
                        v-model="item.checked"
                        @change="
                          handleChange($event, item as TableColumnData, index)
                        "
                      >
                      </a-checkbox>
                    </div>
                    <div class="title">
                      {{ item.title === '#' ? '序列号' : item.title }}
                    </div>
                  </div>
                </div>
              </template>
            </a-popover>
          </a-tooltip>
        </a-col>
      </a-row>
      <a-table
        row-key="id"
        column-resizable
        :loading="loading"
        :pagination="pagination"
        :columns="(cloneColumns as TableColumnData[])"
        :scroll="{ x: 1700, y: 2000 }"
        :data="teamIncome"
        :bordered="{ wrapper: true, cell: true }"
        :size="size"
        @page-change="onPageChange"
      >
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 + (pagination.page - 1) * pagination.limit }}
        </template>
        <template #money="{ record }">
          <a-space>
            <icon-arrow-rise v-if="record.type !== 2" style="color: #1FE212;" />

            <span :style="{ color: record.type === 2 ? 'red' : '#1FE212'}">
              {{ record.money }}
            </span>
            <icon-arrow-fall v-if="record.type === 2" style="color: red" />

          </a-space>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive, watch, nextTick } from 'vue';
  import { useI18n } from 'vue-i18n';
  import useLoading from '@/hooks/loading';
  import { GetMyIncomeListApi, PolicyRecord } from '@/api/team';
  import { Pagination } from '@/types/global';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import cloneDeep from 'lodash/cloneDeep';
  import Sortable from 'sortablejs';

  type SizeProps = 'mini' | 'small' | 'medium' | 'large';
  type Column = TableColumnData & { checked?: true };

  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const formModel = reactive<any>({
    nickname: '',
    mobile: '',
    type: 1,
  });
  const teamIncome = ref<PolicyRecord[]>([]);

  const cloneColumns = ref<Column[]>([]);
  const showColumns = ref<Column[]>([]);

  const size = ref<SizeProps>('medium');

  // 分页属性
  const basePagination: Pagination = {
    page: 1,
    limit: 10,
  };
  const pagination = reactive({
    ...basePagination,
  });
  // 定义尺寸
  const densityList = computed(() => [
    {
      name: t('teamIncome.size.mini'),
      value: 'mini',
    },
    {
      name: t('teamIncome.size.small'),
      value: 'small',
    },
    {
      name: t('teamIncome.size.medium'),
      value: 'medium',
    },
    {
      name: t('teamIncome.size.large'),
      value: 'large',
    },
  ]);
  // 查询结果 每列标题与字段
  const columns = computed<TableColumnData[]>(() => [
    {
      title: t('teamIncome.columns.index'),
      dataIndex: 'index',
      slotName: 'index',
      width: 50,
      align: 'center',
    },
    {
      title: t('teamIncome.columns.nickname'),
      dataIndex: 'user.nickname',
      align: 'center',
      width: 200,
      ellipsis:true,
      tooltip:true
    },

    {
      title: t('teamIncome.columns.mobile'),
      dataIndex: 'user.mobile',
      align: 'center',
      width: 200,

    },
    {
      title: t('teamIncome.columns.all_money'),
      dataIndex: 'all_money',
      align: 'center',
      width:180,

    },
    {
      title: t('teamIncome.columns.money'),
      dataIndex: 'money',
      slotName: 'money',
      align: 'center',
      width:150,
    },
    {
      title: t('teamIncome.columns.before'),
      dataIndex: 'before',
      align: 'center',
      width:150,
    },
    {
      title: t('teamIncome.columns.after'),
      dataIndex: 'after',
      align: 'center',
      width:150,
    },
    {
      title: t('teamIncome.columns.memo'),
      dataIndex: 'memo',
      align: 'center',
    },
    {
      title: t('teamIncome.columns.createtime'),
      dataIndex: 'createtime',
      align: 'center',
      width:200,
    },
  ]);

  // 查询/筛选 列表
  const fetchData = async () => {
    const params = {
      ...basePagination,
      ...formModel,
    };

    setLoading(true);
    try {
      const { data } = await GetMyIncomeListApi(params);
      teamIncome.value = data.data;
      pagination.page = params.page;
      pagination.total = data.total;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };

  const search = () => {
    fetchData();
  };
  search();

  const onPageChange = (page: number) => {
    basePagination.page = page;
    fetchData();
  };
  const reset = () => {
    formModel.nickname = '';
    formModel.mobile = '';
    basePagination.page = 1;
    fetchData();
  };

  const handleSelectDensity = (
    val: string | number | Record<string, any> | undefined,
    e: Event
  ) => {
    size.value = val as SizeProps;
  };

  const handleChange = (
    checked: boolean | (string | boolean | number)[],
    column: Column,
    index: number
  ) => {
    if (!checked) {
      cloneColumns.value = showColumns.value.filter(
        (item) => item.dataIndex !== column.dataIndex
      );
    } else {
      cloneColumns.value.splice(index, 0, column);
    }
  };

  const exchangeArray = <T extends Array<any>>(
    array: T,
    beforeIdx: number,
    newIdx: number,
    isDeep = false
  ): T => {
    const newArray = isDeep ? cloneDeep(array) : array;
    if (beforeIdx > -1 && newIdx > -1) {
      // 先替换后面的，然后拿到替换的结果替换前面的
      newArray.splice(
        beforeIdx,
        1,
        newArray.splice(newIdx, 1, newArray[beforeIdx]).pop()
      );
    }
    return newArray;
  };

  const popupVisibleChange = (val: boolean) => {
    if (val) {
      nextTick(() => {
        const el = document.getElementById('tableSetting') as HTMLElement;
        const sortable = new Sortable(el, {
          onEnd(e: any) {
            const { oldIndex, newIndex } = e;
            exchangeArray(cloneColumns.value, oldIndex, newIndex);
            exchangeArray(showColumns.value, oldIndex, newIndex);
          },
        });
      });
    }
  };

  watch(
    () => columns.value,
    (val) => {
      cloneColumns.value = cloneDeep(val);
      cloneColumns.value.forEach((item, index) => {
        item.checked = true;
      });
      showColumns.value = cloneDeep(cloneColumns.value);
    },
    { deep: true, immediate: true }
  );
</script>

<script lang="ts">
  export default {
    name: 'List',
  };
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }

  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }

  .action-icon {
    margin-left: 12px;
    cursor: pointer;
  }

  .active {
    color: #0960bd;
    background-color: #e3f4fc;
  }

  .setting {
    display: flex;
    align-items: center;
    width: 200px;

    .title {
      margin-left: 12px;
      cursor: pointer;
    }
  }
</style>
